import { useState, useEffect } from 'react';
import { Table, Input, Button, Form, Row, Col, Card, Space, App, Modal } from 'antd';
import { getRoleList, deleteRole, addRole, updateRole, getRoleById } from '@/api/role';
import AuthControl from '@/components/common/AuthControl';
import hasElementAuth from '@/utils/auth';
import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined, SettingOutlined } from '@ant-design/icons';
import RoleForm from './RoleForm';
import RolePermissionConfig from './RolePermissionConfig';

const RoleIndex = () => {
  const [form] = Form.useForm();
  const [addEditForm] = Form.useForm();
  const { modal, message } = App.useApp();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [drawerLoading, setDrawerLoading] = useState(false);
  
  const getColumns = () => {
    const baseColumns = [
      {
        title: '角色编码',
        dataIndex: 'roleCode',
        key: 'roleCode'
      },
      {
        title: '角色名称',
        dataIndex: 'roleName',
        key: 'roleName'
      }
    ];

    if(hasElementAuth(['edit','delete'])){
      baseColumns.push(
        {
          title: '操作',
          key: 'action',
          width: 300,
          render: (_, record) => (
            <Space>
              <AuthControl permission="edit">
                <Button icon={<EditOutlined />} onClick={() => openEditModal(record)}>编辑</Button>
              </AuthControl>
              <AuthControl permission="roleConfig">
                <Button icon={<SettingOutlined />} onClick={() => openPermissionConfig(record)}>权限配置</Button>
              </AuthControl>
              <AuthControl permission="delete">
                <Button icon={<DeleteOutlined />} onClick={()=>deleteById(record.roleId)} danger>删除</Button>
              </AuthControl>
            </Space >
          )
        }
      );
    }
    
    return baseColumns;
  };

  const [searchForm, setSearchForm] = useState({
    roleCode: "",
    roleName: "",
    size: 10,
    current: 1
  });
  
  const [permissionConfigVisible, setPermissionConfigVisible] = useState(false);
  const [currentRoleId, setCurrentRoleId] = useState('');
  
  const [total, setTotal] = useState(0);
  const [tableData, setTableData] = useState([]);
  const [loading, setLoading] = useState(false);

  /**
   * 查询角色列表
   */
  const searchRoles = (formData) => {
    setLoading(true);
    const params = formData || searchForm;
    getRoleList(params)
      .then(res => {
        if (res.data && res.data.others) {
          setTableData(res.data.others);
          setTotal(res.data.total || 0);
        } else {
          setTableData([]);
          setTotal(0);
        }
      })
      .finally(() => {
        setLoading(false);
      });
  };
  
  /**
   * 删除角色
   */
  const deleteById = (id) => {
    modal.confirm({
      title: '确定要删除吗？',
      content: '此操作将永久删除该数据，请谨慎操作。',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        setLoading(true);
        deleteRole({id:id}).then(() => {
          message.success("角色信息已删除");
          searchRoles();
          })
          .finally(() => {
            setLoading(false);
          });
      }
    });
  };
  
  /**
   * 打开新增模态框
   */
  const openAddModal = () => {
    setIsEditing(false);
    addEditForm.resetFields();
    setIsModalOpen(true);
  };
  
  /**
   * 打开编辑模态框
   */
  const openEditModal = (record) => {
    setDrawerLoading(true);
    setIsEditing(true);
    setIsModalOpen(true);
    
    // 调用接口获取详细信息
    getRoleById({id: record.roleId}).then(res => {
      if (res.data) {
        addEditForm.setFieldsValue({
          roleId: res.data.roleId,
          roleCode: res.data.roleCode,
          roleName: res.data.roleName,
          remark: res.data.remark
        });
      }
    })
    .finally(() => {
      setDrawerLoading(false);
    });
  };
  
  /**
   * 关闭模态框
   */
  const closeModal = () => {
    setIsModalOpen(false);
    addEditForm.resetFields();
    setIsEditing(false);
  };
  
  /**
   * 保存角色数据
   */
  const saveRoleData = () => {
    addEditForm.validateFields().then(values => {
      setDrawerLoading(true);
      if (isEditing) {
        // 修改
        const updateData = {
          roleId: values.roleId,
          roleName: values.roleName,
          remark: values.remark
        };
        updateRole(updateData).then(() => {
          message.success("角色信息已更新");
          closeModal();
          searchRoles();
        })
        .finally(() => {
          setDrawerLoading(false);
        });
      } else {
        // 新增
        const addData = {
          roleCode: values.roleCode,
          roleName: values.roleName,
          remark: values.remark
        };
        addRole(addData).then(() => {
          message.success("新角色已添加");
          closeModal();
          searchRoles();
        })
        .finally(() => {
          setDrawerLoading(false);
        });
      }
    })
  };

  useEffect(() => {
    searchRoles();
  }, []);

  const handleTableChange = (pagination) => {
    const formData = {
      ...searchForm,
      current: pagination.current,
      size: pagination.pageSize
    };
    
    // 如果pageSize发生变化，重置到第一页
    if (pagination.pageSize !== searchForm.size) {
      formData.current = 1;
    }
    
    setSearchForm(formData);
    searchRoles(formData);
  };

  const handleSearch = (values) => {
    const formData = {
      ...searchForm,
      roleCode: values.roleCode || "",
      roleName: values.roleName || "",
      current: 1
    };
    setSearchForm(formData);
    searchRoles(formData);
  };

  /**
   * 打开权限配置模态框
   */
  const openPermissionConfig = (record) => {
    setCurrentRoleId(record.roleId);
    setPermissionConfigVisible(true);
  };
  
  /**
   * 关闭权限配置模态框
   */
  const closePermissionConfig = () => {
    setPermissionConfigVisible(false);
    setCurrentRoleId('');
  };
  
  /**
   * 保存权限配置
   */
  const handlePermissionConfigConfirm = () => {
    closePermissionConfig();
  };

  return (
    <Card>
      <AuthControl permission="search">
        <Form form={form} onFinish={handleSearch}>
          <Row gutter={24}>
            <Col span={8}>
              <Form.Item name="roleCode" label="角色编码">
                <Input placeholder="请输入角色编码" allowClear/>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="roleName" label="角色名称">
                <Input placeholder="请输入角色名称" allowClear/>
              </Form.Item>
            </Col>
            <Col span={8} style={{ textAlign: 'right' }}>
              <Form.Item>
                  <Button type="primary" htmlType="submit" loading={loading} icon={<SearchOutlined />} style={{ marginRight: 8 }}>
                    查询
                  </Button>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </AuthControl>
      <AuthControl permission="add">
        <Button loading={loading} type="primary" icon={<PlusOutlined />} style={{ marginBottom: 16 }} onClick={openAddModal}>
          添加
        </Button>
      </AuthControl>
      <Table 
        columns={getColumns()}
        dataSource={tableData} 
        rowKey="roleId" 
        loading={loading}
        scroll={{ y: '45vh' }}
        pagination={{
          current: searchForm.current,
          pageSize: searchForm.size,
          total: total,
          showTotal: (total) => `共 ${total} 条数据`,
          showSizeChanger: true,
          pageSizeOptions: ['5','10', '20', '50', '100']
        }}
        onChange={handleTableChange}
      />
      
      {/* 新增/编辑模态框 */}
      <Modal
        title={isEditing ? "编辑角色" : "新增角色"}
        open={isModalOpen}
        onCancel={closeModal}
        confirmLoading={drawerLoading}
        onOk={saveRoleData}
        okText="保存"
        cancelText="取消"
      >
        <RoleForm form={addEditForm} isEditing={isEditing} />
      </Modal>
      
      {/* 权限配置模态框 */}
      <RolePermissionConfig 
        visible={permissionConfigVisible}
        roleId={currentRoleId}
        onCancel={closePermissionConfig}
        onConfirm={handlePermissionConfigConfirm}
      />
    </Card>
  );
};

export default RoleIndex;